/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gridworld_v5;

import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Student
 */
public class ThreadedCritter extends ThreadedActor{
    ////<editor-fold defaultstate="collapsed" desc="Instanced Variables">
    private List<Tile> safeTiles = new LinkedList();
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Constructor">
    public ThreadedCritter(Game game, Board board, Tile tile) {
        super(game, board, tile);
        super.actorType = PossibleStates.Critter;
    }
    //</editor-fold>
    ////<editor-fold defaultstate="collapsed" desc="Abstract Override Methods">
    @Override
    public void checkSafeTiles() {
        List<Tile> unsafeTiles = new LinkedList();
        List<Tile> buggedTiles = new LinkedList();
        safeTiles.clear();
        safeTiles.addAll(currentTile.getNeighbors());
        for (Tile t: safeTiles){
            for (ThreadedActor ta : t.getOccupants()){
                if ( ta.isTypeOf(PossibleStates.Rock) ||  ta.isTypeOf(PossibleStates.Critter)){
                    //safeTiles.remove(t);
                    unsafeTiles.add(t);
                }
            }
        }
        safeTiles.removeAll(unsafeTiles);
        for (Tile t: safeTiles){
            if (
                (t.getTileState().equals(PossibleStates.Bug)) ||
                (t.getTileState().equals(PossibleStates.Bug))
            ){
                buggedTiles.add(t);
            }
        }
        if (buggedTiles.size() > 0 ) {
            safeTiles = buggedTiles;
        }
    }

    @Override
    public void run() {

            int index;
            while (!dead){
                //System.out.println("run():" + this);
                checkSafeTiles();
                index = (int) (Math.random()*safeTiles.size());
                System.out.println("Critter" + this + " has moved to tile:" 
                        + (safeTiles.get( index ).getIndex()) 
                        + " : has lived " + lifeSpanPassed() + " milliseconds"
                        );
                moveToTile( safeTiles.get( index ) );
                try {
                    for (ThreadedActor ta : currentTile.getOccupants()) {
                        if (ta.isTypeOf(PossibleStates.Bug)) {
                            ta.killed();
                        }
                    }
                } catch (Exception e) {
                }
                try {
                    //System.out.println("sleep time:" + game.gv.InitialTurnTime);
                    Thread.sleep( (long) (Math.random()*game.gv.InitialTurnTime));

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    }
    //</editor-fold>
}
